import FormBoListApi from "@/api/FormBoList/FormBoListApi";
import Util from "@/js/Util.js"
import Dialog from "@/js/Dialog";
import Api from "@/api/Api";
import shareApi from "@/api/shareApi";
import rxAjax from "@/assets/ajax";
import FormApi from "@/api/modules/form/formApi";
import GatewayApi from "@/api/Gateway/GatewayApi";
export default {
    data() {
        return {
            timer: 0
        }
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "mobileJsLang", key);
        },
        gotoCustomForm(data) {
            this.$emit("close", {action: "cancel"});
            uni.navigateTo({
                url: '/views/modules/form/customForm/FormSolutionShow/FormSolutionComponent?params=' + JSON.stringify(data)
            })
        },
        onMobileAdd() {
            let params = {
                action: "edit",
            }
            params.alias = this.formBoList.formAlias;
            if (this.formBoList.formAddAlias) {
                params.alias = this.formBoList.formAddAlias;
            }
            params['appId'] = Util.getAppId(this);
            params.jsonParams=this.formdata
            this.gotoCustomForm(params);
        },
        //列表编辑
        onMobileEdit(row) {
            let self_ = this;
            if (row.INST_ID_ && row.INST_STATUS_ != "DRAFTED") {
                uni.showToast({
                    title: self_.i18n('bpmRowCannotEdit', '流程审批中或审批完成的记录不能被编辑'), // 消息内容
                    duration: 2000, // 持续时间（单位：毫秒）
                    icon: 'none' // 图标类型（可选值：success/loading/none）
                });
                return
            }
            let params = {
                action: 'edit',
                pk: row.ID_,
            }
            params.alias = this.formBoList.formAlias;
            params['appId'] = Util.getAppId(this);
            this.gotoCustomForm(params);
        },
        //列表删除
        onMobileRemove(row) {
            let exclude = ['DRAFTED','DELETE']
            let self_ = this;
            if(row.INST_ID_ && !exclude.contains(row.INST_STATUS_)){
                uni.showToast({title: self_.i18n('bpmRowCannotDel', '流程审批中或审批完成的记录不能被删除'), icon: 'none'});
                return
            }
            this.onDeleteByFormSolAlias(row)
        },
        //判断是否允许删除列表
        onDeleteByFormSolAlias(row) {
            let self_ = this;
            FormBoListApi.isDeleteByFormSolAlias({
                alias: this.formBoList.formAlias,
                ids: row.ID_
            }).then(res => {
                if (res.success) {
                    let resultData = res.data;
                    var isDelete = true;
                    for (let i = 0; i < resultData.length; i++) {
                        var isBreak = false;
                        var relationData = resultData[i].relationData;
                        for (let j = 0; j < relationData.length; j++) {
                            if (relationData[j].data.length == 0) {
                                isDelete = relationData[j].isDelete;
                            } else {
                                isDelete = false;
                                isBreak = true;
                                break;
                            }
                        }
                        if (isBreak) {
                            break;
                        }
                    }
                    if (isDelete) {
                        //没有配置关联列表可以直接删除
                        uni.showModal({
                            title: self_.$ti18('rxMsa.tips', '提示'),
                            content: self_.i18n('sureDelete', '确认删除该记录?'),
                            confirmText: self_.$ti18('rxForm.okBtn', '确定'),
                            cancelText: self_.$ti18('rxForm.cancelBtn', '取消'),
                            success: function (res) {
                                let params = {
                                    alias: self_.formBoList.formAlias,
                                    id: row.ID_
                                }
                                if (res.confirm) {
                                    FormBoListApi.formSolutionRemoveById(params).then(res => {
                                        if (res.success) {
                                            uni.showToast({
                                                title: res.message,
                                                duration: 1500,
                                                icon: 'none'
                                            });
                                            self_.onRefresh();
                                        } else {
                                            uni.showToast({
                                                title: res.message || self_.$ti18('rxMsa.masWarn.error', '出错了'),
                                                duration: 1500,
                                                icon: 'none'
                                            });
                                        }
                                    })
                                }
                            }
                        });

                    } else {
                        uni.navigateTo({
                            url: "/views/modules/form/formBoList/components/DeletePrompt?resultData=" + JSON.stringify(resultData) + '&formAlias=' + self_.formBoList.formAlias
                        })
                    }
                }
            });
        },
        //打开列表明细
        onMobileDetail(row) {
            let params = {
                action: "detail",
                pk: row.ID_,
            }
            params.alias = this.formBoList.formAlias;
            if (this.formBoList.formDetailAlias) {
                params.alias = this.formBoList.formDetailAlias;
            }
            params['appId'] = Util.getAppId(this);
            this.gotoCustomForm(params);
        },
        /**
         * 使用参数对象打开表单方案.
         * @param {Object} obj 参数对象
         */
        openFormSolution({
            //表单方案别名
            alias,
            //标题
            title,
            //传递表单数据
            params={},
            //回调方法
            destroy,
            //主键
            pk="",
            readOnly=false,
            closeOnSave=true,
            openMode={isMax:true,isShade:true,width:800,height:600}}) {
            this.openForm(alias,title,readOnly,pk,params,destroy);
        },
        /**
         * 打开表单方案
         */
        openForm(alias, title, readonly, pk, params, destroy) {
            let paramsControl = {
                alias: alias,
                action: 'edit',
                pk: pk,
                title:title,
                jsonParams: params,
                appId:Util.getAppId(this)
            }
            if (readonly) {
                paramsControl.action = 'detail';
            }

            let conf = {
                data: {
                    isShowFormDialog: true,
                    paramsControl: paramsControl,
                },
                dialogOptions:{
                    title:title,
                    okText:''
                },
                curVm: this,
            };
            Dialog.openForm(conf, function (data) {
                if(destroy){
                    destroy(data.action, data.data);
                }
            })
        },
        showModal(conf) {
            /**
             * uni.showModal({
             *                 title:  '标题',
             *                 content: '内容',
             *                 confirmText: '确定',
             *                 cancelText: '取消',
             *                 success: function (res) {
             *                     if (res.confirm) {
             *                         console.log('用户点击确认');
             *                     } else if (res.cancel) {
             *                         console.log('用户点击取消');
             *                     }
             *                 }
             *             });
             */
            uni.showModal(conf);
        },
        showToast(title,icon) {
            //图标类型（可选值：error/success/loading/none）
            uni.showToast({
                title: title, duration: 2000, icon: icon?icon:'none'
            });
        },
        /**
         * 调用自定义查询
         */
        invokeCustomQuery(key, params, callback) {
            Api.queryForJson(key, {params: JSON.stringify(params)}).then(res => {
                if (res.success && callback && typeof (callback) == 'function') {
                    callback(res.data);
                }
            });
        },
        /**
         * 调用自定义查询
         */
        invokeCustomQueryPromise(alias,params){
            return shareApi.queryForJson(alias, params);
        },
        /**
         * 调用服务端脚本。
         */
        invokeScript(alias, params, callback) {
            let url="/api-form/form/core/formInvokeScript/invoke/"+alias;
            return  rxAjax.postJson(url,params).then(res=>{
                if(callback) {
                    callback(res);
                }
            })
        },
        /**
         * 调用服务端脚本。
         */
        invokeScriptPromise(alias,params){
            let url="/api-form/form/core/formInvokeScript/invoke/"+alias;
            return  rxAjax.postJson(url,params);
        },
        /**
         * 发送post请求。
         */
        postJson(url, params) {
            return rxAjax.postJson(url, params);
        },
        /**
         * 发送get请求。
         */
        get(url) {
            return rxAjax.get(url);
        },
        /**
         * ajax
         * @returns {Request}
         */
        getAjax() {
            return rxAjax;
        },
        /**
         * 发送 post 请求。
         *  两种方式 ： 对象 {name:"RAY"} 传键值对 name=ray
         * @param url
         * @param params
         */
        postForm(url, params) {
            if(typeof params =="object"){
                let tmpAry=[];
                for(let key in params){
                    tmpAry.push(key +"=" + params[key]);
                }
                params=tmpAry.join("&");
            }
            return rxAjax.post(url, params);
        },
        /**
         * 延迟执行。
         * @param callBack
         * @param timeout
         */
        delay(callBack,timeout){
            if(this.timer){
                window.clearTimeout(this.timer);
                this.timer=0;
            }
            this.timer=window.setTimeout(callBack,timeout);
        },
        /**
         * 调用接口。
         * @param apiKey
         * @param params
         * @param callback
         */
        invokeInterface(apiKey,params,callback){
            shareApi.formBoListInterface(apiKey,params).then(res=>{
                if(callback){
                    callback(res);
                }
            })
        },
        getValue(value){
            if(value){
                let val = new Function( "return " + value )();
                return val.value ;
            }
            return ''
        },
        getLabel(value) {
            if(value){
                let val = new Function( "return " + value )();
                return val.label ;
            }
        },
        //获取选中行的数据
        getSelectedRows(){
            return  this.$refs.table.checkeds
        },
        /**
         * 执行规则引擎
         * @param liteFlowId
         * @param params
         * @returns {*}
         */
        executeLiteFlow(liteFlowId, params){
            return FormApi.executeLiteFlow(liteFlowId, params);
        },
        /**
         * @param obj
         * alias： 别名
         * params：参数
         * title:名称
         * config:{max:true,shade:true,width:200,height:200)}
         * callBack：回调函数
         */
        openCustomPage(alias,params,title,config,callBack){
            let paramsObj = {
                alias:alias,
                params:params,
                title:title,
                appId:Util.getAppId(this)
            }
            Dialog.openCustomPage(paramsObj,callBack)
            let res = {}
            if(callBack){
                callBack(res);
            }
        },
    }
}
